package com.kmproject.haifu.mvp.ui.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jess.arms.base.App;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.http.imageloader.glide.ImageConfigImpl;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.utils.PermissionUtil;
import com.jess.arms.widget.autolayout.AutoToolbar;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.app.utils.Glide4Engine;
import com.kmproject.haifu.di.component.DaggerUserSetEditInfoComponent;
import com.kmproject.haifu.mvp.contract.UserSetEditInfoContract;
import com.kmproject.haifu.mvp.model.entity.User;
import com.kmproject.haifu.mvp.model.entity.beans.UserBean;
import com.kmproject.haifu.mvp.model.entity.beans.UserLoginBean;
import com.kmproject.haifu.mvp.presenter.UserSetEditInfoPresenter;
import com.kmproject.haifu.mvp.ui.widget.CircleImageView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 06/24/2019 11:47
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class UserSetEditInfoActivity extends BaseActivity<UserSetEditInfoPresenter> implements UserSetEditInfoContract.View {

    @BindView(R.id.toolbar_back)
    RelativeLayout toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.back_right_icon)
    ImageView backRightIcon;
    @BindView(R.id.back_right_txt)
    TextView backRightTxt;
    @BindView(R.id.toolbar_right)
    RelativeLayout toolbarRight;
    @BindView(R.id.toolbar)
    AutoToolbar toolbar;
    @BindView(R.id.completeUserInfo_header_img)
    CircleImageView completeUserInfoHeaderImg;
    @BindView(R.id.userSet_update_nc_xtx)
    TextView userSetUpdateNcXtx;
    @BindView(R.id.userSet_editInfo_nc_lay)
    LinearLayout userSetEditInfoNcLay;
    @BindView(R.id.userSet_update_gxqm_xtx)
    TextView userSetUpdateGxqmXtx;
    @BindView(R.id.userSet_editInfo_gxqm_lay)
    LinearLayout userSetEditInfoGxqmLay;
    @BindView(R.id.userSet_update_gxqm_xb)
    TextView userSetUpdateGxqmXb;
    @BindView(R.id.userSet_editInfo_sex_lay)
    LinearLayout userSetEditInfoSexLay;
    RxPermissions mRxPermissions;
    List<Uri> mSelected;
    ImageLoader glideImage;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerUserSetEditInfoComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_user_set_edit_info; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mRxPermissions = new RxPermissions(this);
        toolbar.setBackgroundColor(ArmsUtils.getColor(this, R.color.color_EDEDED));
        if (glideImage == null) {
            glideImage = ArmsUtils.obtainAppComponentFromContext(this).imageLoader();
        }
        mPresenter.qurUserInfo();
    }

    @Override
    public void showLoading() {
        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        loadingDialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.completeUserInfo_header_img, R.id.userSet_editInfo_nc_lay, R.id.userSet_editInfo_gxqm_lay, R.id.userSet_editInfo_sex_lay})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.completeUserInfo_header_img:
                mPresenter.requestPrisession();

                break;
            case R.id.userSet_editInfo_nc_lay:
                intent = new Intent(UserSetEditInfoActivity.this, UserSetEditInfoSetTxtActivity.class);
                intent.putExtra("type", "nc");
                intent.putExtra("data", userSetUpdateNcXtx.getText().toString());
                ArmsUtils.startActivityForResult(intent, AppConstant.START_ACTIVITY_REQUEST_CODE);
                break;
            case R.id.userSet_editInfo_gxqm_lay:
                intent = new Intent(UserSetEditInfoActivity.this, UserSetEditInfoSetTxtActivity.class);
                intent.putExtra("type", "gxqm");
                intent.putExtra("data", userSetUpdateGxqmXtx.getText().toString());
                ArmsUtils.startActivityForResult(intent, AppConstant.START_ACTIVITY_REQUEST_CODE);
                break;
            case R.id.userSet_editInfo_sex_lay:
                intent = new Intent(UserSetEditInfoActivity.this, UserSetEditInfoSetTxtActivity.class);
                intent.putExtra("type", "sex");
                intent.putExtra("data", userSetUpdateGxqmXb.getText().toString());
                ArmsUtils.startActivityForResult(intent, AppConstant.START_ACTIVITY_REQUEST_CODE);
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == AppConstant.START_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
            UserBean userBean = DataHelper.getDeviceData(this, AppConstant.USER_INFO);//获取用户信息
            if (data.getStringExtra("type").equals("nc")) {
                userSetUpdateNcXtx.setText(data.getStringExtra("data"));
                userBean.setNickName(data.getStringExtra("data"));
            } else if (data.getStringExtra("type").equals("gxqm")) {
                userSetUpdateGxqmXtx.setText(data.getStringExtra("data"));
                userBean.setUserDesc(data.getStringExtra("data"));
            } else {
                //性别选择
                userSetUpdateGxqmXb.setText(data.getStringExtra("data"));
//                userBean.set(data.getStringExtra("data"));
            }
            DataHelper.saveDeviceData(this, AppConstant.USER_INFO, userBean);
        } else if (data != null && requestCode == AppConstant.REQUEST_CODE_CHOOSE) {
            mSelected = Matisse.obtainResult(data);
            if (mSelected != null && !mSelected.isEmpty()) {
                AppUtil.getBitmapFromUri(this, mSelected.get(0));
            }
            Log.d("Matisse", "mSelected: " + mSelected);
            if (!mSelected.isEmpty()) {
                completeUserInfoHeaderImg.setImageURI(mSelected.get(0));
                String path = AppUtil.getFromMediaUri(this, getContentResolver(), mSelected.get(0));
                if (!TextUtils.isEmpty(path)) {
                    File file = new File(path);
                    if (file != null && file.exists()) {
                        Luban.with(this)
                                .load(file)
                                .ignoreBy(100)
                                //                                .setTargetDir()
                                .filter(new CompressionPredicate() {
                                    @Override
                                    public boolean apply(String path) {
                                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                                    }
                                })
                                .setCompressListener(new OnCompressListener() {
                                    @Override
                                    public void onStart() {
                                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                                    }

                                    @Override
                                    public void onSuccess(File file) {
                                        // TODO 压缩成功后调用，返回压缩后的图片文件
                                        glideImage.loadImage(UserSetEditInfoActivity.this, ImageConfigImpl.builder().url(file.getPath()).imageRadius(5)
                                                .imageView(completeUserInfoHeaderImg)
                                                .build());
                                        //上传图片
                                        mPresenter.updateHeadImg(completeUserInfoHeaderImg, file);
//                                        creatPublishNongHuHolder.addpath(file.getPath());


                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        // TODO 当压缩过程出现问题时调用
                                    }
                                }).launch();

                    }
                }

            }
        }
    }

    @Override
    public RxPermissions getPermissions() {
        return mRxPermissions;
    }

    @Override
    public void requestPerimissionSuccess() {
        //拍照界面
        Matisse.from(UserSetEditInfoActivity.this)
                .choose(MimeType.ofImage())
                .countable(true)
                .capture(true)
                .captureStrategy(
//                new CaptureStrategy(true, "com.lxc.inspectionmanagement.fileprovider"))
                        new CaptureStrategy(true, "com.kmproject.haifu.fileprovider"))
                .maxSelectable(1)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new Glide4Engine())
                .forResult(AppConstant.REQUEST_CODE_CHOOSE);
    }

    @Override
    public void qurUserInfoSuccess(UserBean userBean) {
        if (userBean == null) {
            return;
        }
        if (!TextUtils.isEmpty(userBean.getAvatar())) {
            glideImage.loadImage(this, ImageConfigImpl.builder().url(userBean.getAvatar()).imageRadius(5)
                    .imageView(completeUserInfoHeaderImg)
                    .build());

        }
        userSetUpdateNcXtx.setText(userBean.getNickName());
        if (userBean.getUserSex()==null||TextUtils.isEmpty(userBean.getUserSex()))
        {
            userSetUpdateGxqmXb.setText("");
        }else {
            userSetUpdateGxqmXb.setText(userBean.getUserSex());
        }


    }

    @Override
    public void updHeadPortraitSuccess(String path) {

    }

    @Override
    public void updHeadPortraitSuccessForServer(String path) {
        UserBean user = DataHelper.getDeviceData(this, AppConstant.USER_INFO);
        if (user != null) {
            user.setAvatar(path);
            DataHelper.saveDeviceData(this, AppConstant.USER_INFO, user);
        }
    }
}
